package me.zhengjie.minbearwcs.serivce.mission.processor.outbound;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.config.inf.WcsParamConfigDao;
import me.zhengjie.minbearwcs.dao.mission.inf.WcsMissionDao;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundTaskRecordDao;
import me.zhengjie.minbearwcs.dao.outbound.inf.OutboundTaskRecordHistoryDao;
import me.zhengjie.minbearwcs.dao.storage.inf.SmallStorageDao;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.AgvActionSource;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.AgvTaskSource;
import me.zhengjie.minbearwcs.entity.DTO.agv.task.actionEnum.AgvAction;
import me.zhengjie.minbearwcs.entity.DTO.transfer.Tuple;
import me.zhengjie.minbearwcs.entity.PO.agv.missionEnum.AgvMissionType;
import me.zhengjie.minbearwcs.entity.PO.config.WcsParamConfig;
import me.zhengjie.minbearwcs.entity.PO.config.WcsParamConfigContentPool;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.WcsMission;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.status.OutboundAfterSortMissionStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.status.OutboundAfterSortMissionStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.mission.type.MissionType;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.history.OutboundStockUpRecordHistory;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.history.OutboundTaskRecordHistory;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.record.OutboundTaskRecord;
import me.zhengjie.minbearwcs.entity.PO.wcs.outbound.stockUp.OutboundStockUpRecord;
import me.zhengjie.minbearwcs.entity.PO.wcs.storage.SmallStorage;
import me.zhengjie.minbearwcs.entity.PO.wcs.storage.type.StorageType;
import me.zhengjie.minbearwcs.resource.WcsResource;
import me.zhengjie.minbearwcs.serivce.agv.task.agvTask.AgvTaskDispatcher;
import me.zhengjie.minbearwcs.serivce.mission.locker.StorageLockCollector;
import me.zhengjie.minbearwcs.serivce.mission.processor.MissionProcessor;
import me.zhengjie.minbearwcs.serivce.mission.processor.MissionProcessorCommonUtil;
import me.zhengjie.minbearwcs.serivce.mission.storageProcessor.locker.Floor1.Storage1FLocker;
import me.zhengjie.minbearwcs.utils.ContentPool;
import me.zhengjie.minbearwcs.utils.IdWorker;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class OutboundAfterSortMissionProcessor implements MissionProcessor {

    private final AgvTaskDispatcher getPutTaskDispatcher;
    private final TransactionTemplate transactionTemplate;
    private final WcsMissionDao wcsMissionDao;
    private final WcsResource wcsResource;
    private final IdWorker idWorker;
    private final MissionProcessorCommonUtil commonUtil;
    private final OutboundTaskRecordDao outboundTaskRecordDao;
    private final WcsParamConfigDao wcsParamConfigDao;
    private final Storage1FLocker storage1FLocker;
    private final SmallStorageDao smallStorageDao;
    private final OutboundTaskRecordHistoryDao outboundTaskRecordHistoryDao;

    private final Object lock = new Object();

    @Override
    public MissionType getMissionType() {
        return MissionType.OUTBOUND_AFTER_SORT;
    }

    @Override
    public void process(WcsMission missionInfo) {
        OutboundAfterSortMissionStatus missionStatus = (OutboundAfterSortMissionStatus) missionInfo.getEnumMissionStatus();

        switch (missionStatus) {
            case WAIT_FOR_STORAGE:
                searchStorage(missionInfo);
                break;
            case SEARCHING_STORAGE:
                break;
            case WAIT_FOR_DISPATCH:
                dispatchAgvTask(missionInfo);
                break;
            case DISPATCHING:
                break;
            case PROCESSING:
                monitorMission(missionInfo);
                break;
            case FINISH:
                finishWcsMission(missionInfo);
                break;
            case CANCEL:
                break;
        }
    }

    public OutboundTaskRecord getOutboundTaskRecord(String recordId) {
        return outboundTaskRecordDao.selectByOutboundRecordId(recordId);
    }


    private void searchStorage(WcsMission missionInfo) {
        boolean statusChangeSearchStorage = statusChangeSearchStorage(missionInfo.getId());
        if (!statusChangeSearchStorage) {
            return;
        }

        Boolean res = false;

        synchronized (StorageLockCollector.lockStorage1F){
            res = transactionTemplate.execute(status -> {
                try {
                    OutboundTaskRecord outboundTaskRecord = getOutboundTaskRecord(missionInfo.getAssociatedDetailId());
                    WcsParamConfig wcsParamConfig = wcsParamConfigDao.selectByKey(WcsParamConfigContentPool.OUTBOUND_DESTINATION_TYPE);
                    StorageType storageType = StorageType.valueOf(wcsParamConfig.getConfigValue());

                    Tuple<String> tuple = Tuple.tuple(null, false);
                    if (StorageType.WHARF_1F == storageType) {
                        tuple = storage1FLocker.lockWharfStorage(outboundTaskRecord.getPalletCode(), outboundTaskRecord.getLogisticsCompanyCode());
                    } else if (StorageType.LIFT_EXIT_1F == storageType) {
                        tuple = storage1FLocker.lockLiftExitStorage(outboundTaskRecord.getPalletCode());
                    }


                    if (tuple.success) {
                        outboundTaskRecordDao.updateDestinationInfoByRecordId(
                                outboundTaskRecord.getOutboundRecordId(),
                                1,
                                tuple.value
                        );
                        return true;
                    }
                } catch (Exception e) {
                    log.error("wcs任务{}，1F储位锁定失败", missionInfo.getMissionId(), e);
                    status.setRollbackOnly();
                }
                return false;
            });
        }


        if (Boolean.TRUE.equals(res)) {
            wcsMissionDao.updateMissionStatusById(
                    missionInfo.getId()
                    , OutboundAfterSortMissionStatus.WAIT_FOR_DISPATCH.name()
            );
        } else {
            wcsMissionDao.updateMissionStatusById(
                    missionInfo.getId()
                    , OutboundAfterSortMissionStatus.WAIT_FOR_STORAGE.name()
            );
        }


    }

    public boolean statusChangeSearchStorage(Integer missionId) {
        if (OutboundAfterSortMissionStatus.WAIT_FOR_STORAGE == wcsMissionDao.selectMissionStatusById(missionId)) {
            synchronized (lock) {
                if (OutboundAfterSortMissionStatus.WAIT_FOR_STORAGE == wcsMissionDao.selectMissionStatusById(missionId)) {
                    return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
                        try {
                            wcsMissionDao.updateMissionStatusById(missionId, OutboundAfterSortMissionStatus.SEARCHING_STORAGE.name());
                            wcsMissionDao.updateStartTime(missionId, LocalDateTime.now());
                            return true;
                        } catch (Exception e) {
                            log.error("wcs任务状态转换出错", e);
                            status.setRollbackOnly();
                        }
                        return false;
                    }));
                }
            }
        }

        return false;
    }


    public boolean statusChangeDISPATCHING(Integer missionId) {
        if (OutboundAfterSortMissionStatus.WAIT_FOR_DISPATCH == wcsMissionDao.selectMissionStatusById(missionId)) {
            synchronized (lock) {
                if (OutboundAfterSortMissionStatus.WAIT_FOR_DISPATCH == wcsMissionDao.selectMissionStatusById(missionId)) {
                    return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
                        try {
                            wcsMissionDao.updateMissionStatusById(missionId, OutboundAfterSortMissionStatus.DISPATCHING.name());
                            return true;
                        } catch (Exception e) {
                            log.error("wcs任务状态转换出错", e);
                            status.setRollbackOnly();
                        }
                        return false;
                    }));
                }
            }
        }

        return false;
    }


    public void dispatchAgvTask(WcsMission missionInfo) {
        if (!statusChangeDISPATCHING(missionInfo.getId())) return;

        OutboundTaskRecord outboundTaskRecord = getOutboundTaskRecord(missionInfo.getAssociatedDetailId());


        wcsResource.getExecutor().execute(() -> {
            Boolean executeRes = transactionTemplate.execute(status -> {
                try {
                    // 找endPass
                    List<SmallStorage> smallStorageList = smallStorageDao.selectSmallStorageByMediunStorage(outboundTaskRecord.getDestinationSmallStorage());
                    SmallStorage endPassStorage = smallStorageList.stream()
                            .filter(a -> a.getIsEntrance() == ContentPool.STORAGE_IS_ENTER)
                            .findFirst()
                            .orElse(null);
                    String endPass = endPassStorage == null?null:endPassStorage.getSmallStorageCode();

                    String agvTaskId = "Task_Agv_" + idWorker.nextId();
                    AgvTaskSource agvTaskSource = new AgvTaskSource(agvTaskId, AgvMissionType.OUTBOUND_TYPE, 1, missionInfo.getMissionId(), missionInfo.getMissionType(),
                            OutboundAfterSortMissionStatus.PROCESSING.name(), outboundTaskRecord.getPalletCode(),null,endPass);
                    agvTaskSource.addAction(new AgvActionSource(outboundTaskRecord.getStartSmallStorage(), AgvAction.GET))
                            .addAction(new AgvActionSource(outboundTaskRecord.getDestinationSmallStorage(), AgvAction.PUT));


                    if (getPutTaskDispatcher.dispatch(agvTaskSource)) {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), OutboundAfterSortMissionStatus.PROCESSING.name());
                    } else {
                        wcsMissionDao.updateMissionStatusById(missionInfo.getId(), OutboundAfterSortMissionStatus.WAIT_FOR_DISPATCH.name());
                    }
                    return true;
                } catch (Exception e) {
                    log.error("wcs任务：{}，生成agv任务失败", missionInfo.getMissionId(), e);
                    status.setRollbackOnly();
                }
                return false;
            });

            if (Boolean.FALSE.equals(executeRes)) {
                wcsMissionDao.updateMissionStatusById(missionInfo.getId(), OutboundAfterSortMissionStatus.WAIT_FOR_DISPATCH.name());
            }

        });
    }


    public void monitorMission(WcsMission missionInfo) {

    }

    public void finishWcsMission(WcsMission missionInfo) {
        transactionTemplate.executeWithoutResult(status -> {
            try {
                OutboundTaskRecord outboundTaskRecord = getOutboundTaskRecord(missionInfo.getAssociatedDetailId());
                if (outboundTaskRecord.getOutboundOrderCode() == null) {
                    outboundTaskRecordHistoryDao.insert(
                            new OutboundTaskRecordHistory(null, outboundTaskRecord.getOutboundRecordId(), outboundTaskRecord.getOutboundOrderCode(),
                                    outboundTaskRecord.getOutboundOrderDetailId(), outboundTaskRecord.getPalletCode(), outboundTaskRecord.getMaterialCode(),
                                    outboundTaskRecord.getMaterialNum(), outboundTaskRecord.getStartFloorNum(), outboundTaskRecord.getStartSmallStorage(),
                                    outboundTaskRecord.getDestinationFloorNum(), outboundTaskRecord.getDestinationSmallStorage(),
                                    outboundTaskRecord.getIsSort(), outboundTaskRecord.getOriginalPalletMaterialNum(), outboundTaskRecord.getCreateTime(),
                                    outboundTaskRecord.getOriginalSmallStorage(), outboundTaskRecord.getLogisticsCompanyCode())
                    );
                    outboundTaskRecordDao.deleteById(outboundTaskRecord.getId());
                }

                missionInfo.setFinishTime(LocalDateTime.now());
                commonUtil.transformMissionHistory(missionInfo);
            } catch (Exception e) {
                log.error("任务结束错误", e);
                status.setRollbackOnly();
            }
        });

    }
}
